// ////////// RE-EXAM /////////
function changeNumList() {
	updateReExamDate();	
}

function changeOptionList() {
	updateReExamDate();
}

function updateReExamDate() {
	var num = $('#num_list').val();
	var option = $('#option_list').val();
	var input = $('#re_examine_input');
	if (isNaN(num)) {
		input.val($('#num_list :selected').attr('label')).focus();
		return;				
	} else {
		var addition = 0;
		var dateObj = Date.today();		
		if (option == 'day') {
			addition = num;
			dateObj.addDays(addition);
		} else if (option == 'week') {
			addition = num*7;
			dateObj.addDays(addition);
		} else if (option == 'month'){
			input.val(_('After {0} month(s)', num)).focus();
			return; 
		}
		input.val(dateObj.getDayName() + ' ' + dateObj.toShortDateString()).focus();		
	}		 	
}

////////// END RE-EXAM // /////


// //////// RECOMMENDATION //////

function showRecommendation() {	
	var buttons = {};
	buttons[_('Close')] = function() {		
		$(this).dialog('close');		
	};
	buttons[_('Add')] = function() {	
		addRecommendation();
		$(this).dialog('close');		
	};
	generalDialog('recommendationDialog',null,null,null,{
		autoOpen: true,			
		bgiframe: true,
		resizable: true,		
		width: 830,
		height: 370,
		modal: true,
		buttons:buttons
	});	
}

function addRecommendation() {
	var recommendedText = '';	
	$('#recommendationContent :checkbox').each(function() {
		if ($(this).is(':checked')) {			
			recommendedText += $('#label_' + $(this).attr('id')).text() + ';\n';			
		}
	});
	if (recommendedText.length > 0) {
		recommendedText = recommendedText.substr(0, recommendedText.length - 2);
		$('#note_input').val(recommendedText); 	
	}		
	$('#note_input').focus();	
}

////////// END RECOMMENDATION ////////////////


////////// ADD PRESCRIPTION TEMPLATE /////////////
function showTemplate() {
	var buttons = {};
	buttons[_('Close')] = function() {		
		$(this).dialog('close');		
	};
	
	generalDialog('prescriptionTemplate',null,null,null,{
		autoOpen: true,			
		bgiframe: true,
		resizable: false,		
		width: 830,
		height: 370,
		modal: true,
		buttons: buttons
	});	
}

function importTemplate(templateId){	
	$.ajax({
		type:	'POST',
		url: 	'../Prescription/importTemplate?set_ajax_view',
		data: 	'templateId=' + templateId +
				'&prescriptionId=' + $('#prescription_id').val(),		
		complete: function() {
			$('#prescriptionTemplate').dialog('close');
		},
		success: function(data) {
			$('#addPrescriptionTable tbody').html(data);			
			displayAutoComplete('row_id_list');
		}
	});	
};

//------------- END ADD PRESCRIPTION TEMPLATE ---------------- //


function displayAutoComplete(idsList){
	var idsList = $('#'+idsList).val();
	idsListArray = idsList.split(';');
	for (var i=0; i<7; i++){		
		$('#' + idsListArray[i] + '_medicine_name_input').autocomplete('../AutoSuggest/DrugMaterialAutoSuggest4DoctorAjax?set_ajax_view', 
				{
					multiple: false,
					matchContains: true,
					autoFill: true,			 
					extraParams: {
		        		enumItemType: function() {
		                    return ''; 
		                    }
		        	}		            
				});	
		$('#' + idsListArray[i] + '_medicine_name_input').result(function(event, data, formatted) {
            if (data != null) {
            	var order = parseInt($(this).attr('id'));
	            $(this).val(data[0]);
	            
	            // auto fill
	            $('input#' + order + '_medicine_id_hidden').val(data[1]);
	            $('select#' + order + '_usage_title').val(data[3]);
	            $('input#' + order + '_usage_num_input').val(data[4]);
	            $('select#' + order + '_dosage_title').val(data[6]);
	            $('input#' + order + '_dosage_input').val(data[7]);
	            $('input#' + order + '_time_input').val(data[8]);
	            $('select#' + order + '_quantity_title').val(data[10]);
	            $('input#' + order + '_quantity_num_input').val(data[11]);
	                        
            }
		});
	}	
}

function loadTemplatePage(controller, action) {
	var url = '../' + controller + '/' + action + '?set_ajax_view';
	$.ajax({
		type: 'GET',
		url: url,
		dataType: 'html',
		success: function(data) {
			$('#pageContent').html(data);
		}
	});
}


function loadPrescription(prescriptionId) {
	if (prescriptionId == 0 ) {
		getNewForm('prescription', 'addPrescriptionTable');		
		return;
	}
	
	$.ajax ({
		type:    "POST",
		url:	  "../Prescription/LoadPrescriptionsAjax?set_ajax_view",
		data: 'prescriptionId=' + prescriptionId,		
		dataType: "json",
		success:	function(data) {
			clearForm();									
			$('table#addPrescriptionTable tbody').html(data.result.form);
			
			displayAutoComplete('row_id_list');	
			$('#prescription_id').val(data.result.prescription_id);
			$('#doctorId').val(data.result.doctor_id);
			$('#doctorName').val(data.result.doctor_name);
			$('#diagnosis').val(data.result.diagnosis);
		}
	});	
	
}

function clearForm() {
	$('#diagnosis').val('');
	$('#clinDiagPrimaryIcd10').val('');
	$('#clinDiagPrimaryDiagnosis').val('');
	
	$('select#doctorId').val(0);	
	$('select#doctorId').css("border-color", "#AAA");
	
	$('input#prescription_id').val('');
	
	$('#successMessage').text('');	
	$('#statusMessage').text('');
}

function getNewForm(type, table){
	$("select#prescriptionSelect").val('0');
	clearForm();	
	
	$.ajax ({
		type: 'GET',
		url: '../Prescription/getNewForm?set_ajax_view',
		data: 'type=' + type +
			  '&recordId=' + $('#record_id').val(),
		dataType: 'json',
		success: function(data) {
			$('#' + table + ' tbody').html(data.newForm);	
			$('#doctorId').val(data.emr.doctorId);
			$('#doctorName').val(data.emr.doctorName);
			$('#diagnosis').val(data.emr.diagnosis);
			
			displayAutoComplete('row_id_list');	
		}
	});
		
};

function validateDrug(row) {
	$('#successMessage').text('');
	$('#statusMessage').text('');
	$('#' + row + '_medicine_name_input').css("border-color", "#AAA");  
	var temp;
	var cur = $.trim($('#' + row + '_medicine_name_input').val());
	if (cur == '') {
		$('select#' + row + '_usage_title').val(0);
		$('select#' + row + '_dosage_title').val(0);
		$('select#' + row + '_quantity_title').val(0);
		$('input#' + row + '_usage_num_input').val('');
		$('input#' + row + '_dosage_input').val('');
		$('input#' + row + '_time_input').val('');
		$('input#' + row + '_quantity_num_input').val('');
		
		$('input#' + row + '_medicine_id_hidden').val('');
		return true;
	}
	//check duplicate
	for ( var int = 0; int < 7; int++) {
		temp = $.trim($('#' + int + '_medicine_name_input').val());
		if (int != row && temp == cur) {
			$('#' + row + '_medicine_name_input').css("border-color", "red");
			showMessage('statusMessage', _('Duplicate drug name [{0}]', cur), 'error');
	   		return false;			
		}
	}
	return true;
}

function validateTemplateBeforeSave() {
	$('#successMessage').text('');
	$('#statusMessage').text('');
	
	if ($.trim($('#templateName').val()) == ''){
		showMessage('statusMessage', _('Please enter template name'), 'error');		
		return false;
	}
	
	var lcF = locale(decimalPoint, thousandSep, 1);
	var nameTemp = '';	
	var tempDup=[];
	for ( var int = 0; int < 7; int++) {
		nameTemp = $.trim($('#' + int + '_medicine_name_input').val());
		$('#' + int + '_medicine_name_input').css("border-color", "#AAA"); 
		
		if (nameTemp != null && nameTemp != '') {
			if (tempDup[nameTemp] != null) {
				$('#' + int + '_medicine_name_input').css("border-color", "red");
				$('#' + int + '_medicine_name_input').focus();
				showMessage('statusMessage', _('Duplicate drug name [{0}]', nameTemp), 'error');
				return false;
			} else {
				tempDup[nameTemp] = 1;				
			}
			
			if (!validateNumberByLocal($('#' + int + '_usage_num_input'), lcF, true, '' , 'statusMessage')) {
				if ($.trim($('#statusMessage').text()) == '') {
					$('#statusMessage').text(_('Require input drug name, usage and quantity'));
				}				
				$('#statusMessage').show();
				return false;
			}			
			if (!checkIntGt(int + '_usage_num_input', 0, 'statusMessage', _('Usage must be greater than 0'))) {
				$('#statusMessage').show();
				return false;
			}
			
			if (!validateNumberByLocal($('#' + int + '_dosage_input'), lcF, false, '' , 'statusMessage')) {
				$('#statusMessage').show();
				return false;
			}
			
			if ($.trim($('#' + int + '_dosage_input').val()) != '' && !checkIntGt(int + '_dosage_input', 0, 'statusMessage', _('Dousage must be greater than 0'))) {
				$('#statusMessage').show();
				return false;
			}
						
			if (!validateNumberByLocal($('#' + int + '_time_input'), lcF, false, '' , 'statusMessage')) {
				$('#statusMessage').show();
				return false;
			}
			
			if ($.trim($('#' + int + '_time_input').val()) != '' && !checkIntGt( int + '_time_input', 0, 'statusMessage', _('Time must be greater than 0'))) {
				$('#statusMessage').show();
				return false;
			}
			
			if (!validateNumberByLocal($('#' + int + '_quantity_num_input'), lcF, true, '' , 'statusMessage')) {
				if ($.trim($('#statusMessage').text()) == '') {
					$('#statusMessage').text(_('Require input drug name, usage and quantity'));
				}
				$('#statusMessage').show();
				return false;
			}
			
			if (!checkIntGt(int + '_quantity_num_input', 0, 'statusMessage', _('Quantity must be greater than 0'))) {
				$('#statusMessage').show();
				return false;
			}
		}
	}
	return true;
}

function validateBeforeSave() {
	$('#successMessage').text('');
	$('#statusMessage').text('');
	
	var lcF = locale(decimalPoint, thousandSep, 1);	
	
	if ($('#doctorId').val() == '' || $.trim($('#doctorName').val()) == ''){
		showMessage('statusMessage', _('Please select doctor'), 'error');		
		return false;
	}
	
	var nameTemp = '';	
	var tempDup=[];
	
	for ( var int = 0; int < 7; int++) {
		nameTemp = $.trim($('#' + int + '_medicine_name_input').val());
		$('#' + int + '_medicine_name_input').css("border-color", "#AAA"); 
		
		if (nameTemp != null && nameTemp != '') {
			if (tempDup[nameTemp] != null) {
				$('#' + int + '_medicine_name_input').css("border-color", "red");
				$('#' + int + '_medicine_name_input').focus();
				showMessage('statusMessage', _('Duplicate drug name [{0}]', nameTemp), 'error');
				return false;
			} else {
				tempDup[nameTemp] = '';				
			}
			
			if (!validateNumberByLocal($('#' + int + '_usage_num_input'), lcF, true, '' , 'statusMessage')) {
				if ($.trim($('#statusMessage').text()) == '') {
					$('#statusMessage').text(_('Require input drug name, usage and quantity'));
				}
				$('#statusMessage').show();  
				
				return false;
			}			
			if (!checkIntGt(int + '_usage_num_input', 0, 'statusMessage', _('Usage must be greater than 0'))) {
				$('#statusMessage').show();
				return false;
			}
			if (!validateNumberByLocal($('#' + int + '_dosage_input'), lcF, false, '' , 'statusMessage')) {
				$('#statusMessage').show();
				return false;
			}
			
			if ($.trim($('#' + int + '_dosage_input').val()) != '' && !checkIntGt(int + '_dosage_input', 0, 'statusMessage', _('Dousage must be greater than 0'))) {
				$('#statusMessage').show();
				return false;
			}
						
			if (!validateNumberByLocal($('#' + int + '_time_input'), lcF, false, '' , 'statusMessage')) {
				$('#statusMessage').show();
				return false;
			}
			
			if ($.trim($('#' + int + '_time_input').val()) != '' && !checkIntGt( int + '_time_input', 0, 'statusMessage', _('Time must be greater than 0'))) {
				$('#statusMessage').show();
				return false;
			}

			
			if (!validateNumberByLocal($('#' + int + '_quantity_num_input'), lcF, true, '' , 'statusMessage')) {
				if ($.trim($('#statusMessage').text()) == '') {
					$('#statusMessage').text(_('Require input drug name, usage and quantity'));
				}
				$('#statusMessage').show();
				return false;
			}
			
			if (!checkIntGt(int + '_quantity_num_input', 0, 'statusMessage', _('Quantity must be greater than 0'))) {
				$('#statusMessage').show();
				return false;
			}
			
			
			
		}
	}
	return true;
}


function submitdeletePrescription(prescriptionId) {
	$.ajax ({
		type:    "POST",
		url:	  "../Prescription/DeletePrescriptionAjax?set_ajax_view",
		data: 'prescriptionId=' + prescriptionId,
		dataType: "json",		
		success:	function(data) {
				if (data.error.code == 'OK') {
					$('select#doctorId').val('0');
					
					$('select#prescriptionSelect :option').each(function(){
						if ($(this).val() == prescriptionId) {
							$(this).remove();							
						}
						
					});
					getNewForm('prescription', 'addPrescriptionTable');															
				} else {
					displayError(data.error.mess);	
				}
		}
	});
	
}
function deletePrescription() {
	var prescriptionId = $('select#prescriptionSelect').val();
	if  ($.trim(prescriptionId) != 0) {
		promptConfirm(
			_("Delete"),
			_("Do you want to delete presciption<span class='impression'>[{0}]</span>?", 
			$('select#prescriptionSelect :selected').text()), 
			function() {
				submitdeletePrescription(prescriptionId); 
				return true;
			},'YesNo','warn',_('No'));
	}	
}

function saveTemplate() {
	if (!validateTemplateBeforeSave()) {
		displayError(_('Error! Please check the input data'));
		return;
	}
		
	var count = 0;
	for ( var int = 0; int < 7; int++) {
		if ($.trim($('input#' + int + '_medicine_name_input').val()) != '') {
			count++;
		}		
	}
	if (count == 0) {
		displayError(_("Please input drug name"));
		return;
	}
	
	var data = $('#templateForm').serialize();
	$.ajax ({
		type:    "POST",
		async:	false,
		url:	  "../Prescription/SaveTemplateAjax?set_ajax_view",
		data: data,
		dataType: "json",
		beforeSend: function() {
			showMessage('successMessage', '', 'success');			
		},
		success:	function(data) {
			if (data.error.code == 'OK') {
				showMessage('successMessage', _('Save successful'), 'success');
				$('input#templateId').val(data.result.template_id);													
			} else {
				displayError(_("Drugs not exist or name not correct: {0}", data.error.mess));	
			}
		}
	});
	
}

function savePrescription(print) {
	if (!validateBeforeSave()) {
		displayError(_('Error! Please check the input data'));
		return;
	}		
	
	var data = $('#prescriptionForm').serialize();
	var count =0;
	for ( var int = 0; int < 7; int++) {
		if ($.trim($('input#' + int + '_medicine_name_input').val()) != '') {
			count++;
		}
		
	}
	if (count == 0) {
		displayError(_("Please input drug name"));
		return;
	}
	
	$.ajax ({
		type:    "POST",
		url:	  "../Prescription/SavePrescriptionAjax?set_ajax_view",
		data: data,
		dataType: "json",
		beforeSend: function() {$('#ajaxLoader').show();},
		complete: function() {$('#ajaxLoader').hide();},
		success:	function(data) {
				if (data.error.code == 'OK') {
					$('#successMessage').css('color', 'green').text(_('Save successful'));
					$('input#prescription_id').val(data.result.prescription_id);
					$('select#prescriptionSelect').html(data.result.prescription_form);
					if (print == 1) {						
						printPres(data.result.prescription_id, $("input[name=langCheck]:checked").val());
					}					
				} else {
					displayError(_("Drugs not exist or name not correct: {0}", data.error.mess));	
				}
		}
	});
	
}

function editTemplate(templateId){		
	// Get the form for new template
	$.ajax({
		type: 'GET',
		url: '../Prescription/editTemplate?set_ajax_view',
		data: 'templateId=' + templateId, 		
		success: function(data) {
			$('#pageContent').html(data);																
		}
	});
	
}

function removeTemplate(){
	promptConfirm(
		_("Delete"),
		_('Are you sure to delete this template?'), 
		function() {
			$.ajax({
				type: 	'POST',
				url: 	'../Prescription/removeTemplate?set_ajax_view',
				data:	'templateId=' + $('#templateId').val(),
				beforeSend: function() {
					$('#ajaxLoader').show();
				},
				complete: function() {
					$('#ajaxLoader').hide();
				},
				success: function(data) {
					loadTemplatePage('Prescription', 'listTemplate');
				}
			});			
			return true;
		},'YesNo', 'warn', _('No'));	
};


function completeNote(elementId) {
	var text = $.trim($('#' + elementId + '_note').val());
	text = text.toLowerCase();	
	if (text.match(/^30$/)) {
		$('#' + elementId + '_note').val("Uống trước ăn 30 phút");
		return;					
	}	
	if (text.match(/^us$/) || text.match(/^ú$/)) {
		$('#' + elementId + '_note').val("Uống sau ăn");
		return;					
	}
	if (text.match(/^ut$/)) {
		$('#' + elementId + '_note').val("Uống trước ăn");
		return;					
	}
	if (text.match(/^ul$/)) {
		$('#' + elementId + '_note').val("Uống lúc ăn");
		return;					
	}
	if (text.match(/^tt$/)) {
		$('#' + elementId + '_note').val("Tra trưa tối trước khi ngủ");
		return;								
	}
	if (text.match(/^stt$/)) {
		$('#' + elementId + '_note').val("Tra sáng trưa tối");
		return;								
	}
	if (text.match(/^stct$/)) {
		$('#' + elementId + '_note').val("Tra sáng trưa chiều tối");
		return;								
	}
	if (text.match(/^t$/)) {
		$('#' + elementId + '_note').val("Tra tối trước khi ngủ");
		return;								
	}	
}

function computeTotal(elementId) {
	var usageNum = convert_number($('#' + elementId + '_usage_num_input').val());
	var dosage = $('#' + elementId + '_dosage_input').val();
	var time = $('#' + elementId + '_time_input').val();
	var dosageTitle = $('#' + elementId + '_dosage_title').val();
	var quantityTitle = $('#' + elementId + '_quantity_title').val();
	if ($.trim(usageNum) != '' && $.trim(dosage) != '' && $.trim(time) != ''
		&& dosageTitle == quantityTitle) {
		var total = Math.round(usageNum * dosage * time);
		$('#' + elementId + '_quantity_num_input').val(total);	
	}
}

function printPres(prescriptionId,lang){	
	var url='../MedicalPrintView/printPrescription?set_print_view&prescriptionId=' 
		+ prescriptionId + '&lang=' + lang;
	window.open(url, '', 'scrollbars=yes, menubar=no, height=700, width=800, resizable=yes, toolbar=no, location=no, status=no');
}